// components/cigarettes-item/cigarettes-item.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {
	canvasId: String,
	width: Number,
	height: Number,
	spec: Object
  },
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function () { 
		setTimeout(() => {
			this.drawCanvas();
		}, 100);
	},
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
	drawCanvas(){
		const { canvasId, width, height, spec } = this.properties;
		const query = wx.createSelectorQuery().in(this);
		query.select('#'+canvasId)
		.fields({ node: true, size: true })
		.exec((res) => {
			const canvas = res[0].node
			const ctx = canvas.getContext('2d')
			const dpr = wx.getSystemInfoSync().pixelRatio
			canvas.width = res[0].width * dpr
			canvas.height = res[0].height * dpr
			ctx.scale(dpr, dpr);
			//计算尺寸
			const isThin = spec.isThin; //是否细支
			const ch = height * (isThin?4/5:3/5);
			const cw = ch*spec.width/spec.height;
			const bottom = (height - ch)/2;
			const cx = width/2 - cw/2;
			const cy = height - ( ch + bottom );
			const filterH =  ch*spec.filterH/spec.height;
			const filterY =  cy + ( ch - filterH );
			const ringH = ch*spec.ringH/spec.height;
			const ringToFilter = ch*spec.ringToFilter/spec.height;
			const ringY = filterY + (ringToFilter || 0);
			const bodyH = ch - filterH;
			ctx.save();
			//绘制香烟体
			ctx.shadowOffsetX = 1;
			ctx.shadowOffsetY = 1;
			ctx.shadowBlur = 10;
			ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
			ctx.fillStyle = spec.bodyColor;
			ctx.fillRect(cx, cy, cw, ch);
			ctx.shadowOffsetX = 0;
			ctx.shadowOffsetY = 0;
			ctx.shadowBlur = 0;
			//绘制过滤嘴
			const w1 = cw;
			const h1 = filterH;
			const x1 = cx;
			const y1 = filterY;
			ctx.fillStyle = spec.filterColor;
			ctx.fillRect(x1, y1, w1, h1);
			//绘制环带
			const w2 = cw;
			const h2 = ringH;
			const x2 = x1;
			const y2 = ringY;
			ctx.fillStyle = spec.ringColor;
			ctx.fillRect(x2, y2, w2, h2);
			//绘制光照渐变
			const lingrad = ctx.createLinearGradient(cx, cy, cx + cw, cy);
			lingrad.addColorStop(0, "rgba(0,0,0,0)");
			lingrad.addColorStop(0.5, "rgba(0,0,0,0.3)");
			lingrad.addColorStop(1, "rgba(0,0,0,0)");
			ctx.fillStyle = lingrad;
			ctx.fillRect(cx, cy, cw, ch);
			ctx.restore();
		})
	}
  }
})